import React from 'react';
import { connect } from 'react-redux';
import debounce from 'lodash.debounce';
import { Table, Input, InputNumber, Form, Spin, Icon, Alert, Popover, Tag, Row, Col, message, Modal, Transfer } from 'antd';
import baseService from 'share/base.service'
const FormItem = Form.Item;
const InputGroup = Input.Group;
import Chooser from 'components/chooser';
import 'styles/my-account/expense-apportion.scss';
import expenseReportService from 'containers/expense-report/expense-report.service';
import chooserData from 'share/chooserData';
import { formatNumber, deepFullCopy, messages, queryCurrencyPrecision, } from 'share/common';
import config from 'config';
import Importer from 'components/template/importer';
import Condition from 'components/condition';
import configureStore from 'stores/index';
import ExpenseTransfer from './components/expense-transfer';
import moment from 'moment';
import ExportModal from "components/template/export-modal/export-modal";
const If = Condition.If;
const { confirm } = Modal;

class ExpenseApportion extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      heights: [],
      costCenterOID: '00000000-0000-0000-0000-000000000000',
      // MCD1009 其他工作餐费
      // MCD1010 部门活动
      columns: [],
      expenseApportion: [],
      defaultExpenseApportion: null,
      users: [],
      scrollX: 450,
      init: false,
      showImportFrame: false,
      tabKey: null,
      initApportionLock: false,
      loadingApplicationApportion: true,
      applicationApportion: null,
      showApplication: false,
      currencyCode: props.currencyCode,
      expenseTypeId: props.expenseTypeId,
      expenseReportOID: props.expenseReportOID,
      expenseTypeCode: props.expenseTypeCode,
      showListSelectVisible: false,
      modalKey: 0,
      isChange: [],
      newCostCenter: [],
      vpAmountList: [],
      deleteList: [],
      selectedRowKeys: undefined
    };
    this.initExpenseApportion = debounce(this.initExpenseApportion, 300);
  }

  componentDidMount() {
    this.initExpenseApportion(this.props, () => this.initColumns(this.props));
    // console.log('this.props', this.props);
  }

  componentWillReceiveProps(nextProps) {
    const { initApportionLock, expenseApportion } = this.state;
    const { actualApportionAmount } = this.props;
    if (!initApportionLock) {
      if (nextProps.expenseTypeId === this.props.expenseTypeId) { //已经清空的分摊行费用详情被修改时，也不会显示默认分摊行
        (expenseApportion.length || !actualApportionAmount && nextProps.actualApportionAmount) && this.initExpenseApportion(nextProps);
      } else {
        this.initExpenseApportion(nextProps, () => this.initColumns(nextProps));
      }
    } else {
      this.initColumns(nextProps)
    }
    console.log(nextProps)
    this.setState({ initApportionLock: false });
  }

  initColumns = (nextProps) => {
    const { readOnly, costCenterItemsApportion } = nextProps;
    let {  defaultExpenseApportion } = this.state;
    let scrollX = 450
    const columns = nextProps.expenseTypeCode === 'MCD1010' || nextProps.expenseTypeCode === 'MCD1009' ? [
      {
        title:  messages('common.sequence'/*序号*/),
        dataIndex: 'index',
        width: 50,
        render: (text, record, index) => <span>{index + 1}</span>
      },
      {
      title: messages('my-account.key15'/*分摊金额*/),
      dataIndex: 'baseCurrencyAmount',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'amount', index)
    }, {
      title: messages('my-account.key16'/*分摊比例*/),
      dataIndex: 'proportion',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'proportion', index)
    },
    {
      title:
        <div className={'requireTitle'}>
          {messages('my-account.key390'/*费用确认人*/)}
        </div>,
      dataIndex: 'personName',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'personName', index)
    },
    {
      title: messages('my-account.key391'/*GM/VP/Office*/),
      dataIndex: 'finalPerson',
      width: 200,
      render: (text, record, index) => this.renderColumns(record, 'finalPerson', index)
    }, {
      title: messages('common.operation')/*操作*/,
      dataIndex: 'operate',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'operate', index)
    }] : [
      {
        title:  messages('common.sequence'/*序号*/),
        dataIndex: 'index',
        width: 50,
        render: (text, record, index) => <span>{index + 1}</span>
      },
      {
      title: messages('my-account.key15'/*分摊金额*/),
      dataIndex: 'baseCurrencyAmount',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'amount', index)
    }, {
      title: messages('my-account.key16'/*分摊比例*/),
      dataIndex: 'proportion',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'proportion', index)
    },
    {
      title:
        <div className={'requireTitle'}>
          {messages('my-account.key390'/*费用确认人*/)}
        </div>,
      dataIndex: 'personName',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'personName', index)
    },
    {
      title: messages('common.operation')/*操作*/,
      dataIndex: 'operate',
      width: 100,
      render: (text, record, index) => this.renderColumns(record, 'operate', index)
    }]
    let arr = this.state.expenseApportion;
    //成本中心
    let costCenterColums = {
      title: <div className={'requireTitle'}>{messages('my-account.key18'/*分摊项*/)}</div>,
      dataIndex: 'costCenterRender',
      width: 400,
      render: (text, record, index) => this.renderColumns(record, 'costCenterRender', index)
    };
    costCenterItemsApportion.length > 0 && (columns.splice(1, 0, costCenterColums), scrollX += 400);
    let isEditable = defaultExpenseApportion && defaultExpenseApportion.isEditable;
    console.log('readOnly', this.props.modeType)
    if (!readOnly && !this.props.modeType) {
      arr.map((e, k) => {
        if (e.costCenterItems[0] && e.costCenterItems[0].costCenterItemOID) {
          // 啊啊啊啊。。。。。。。，恶心
          let params = [{
            costCenterItemOID: k > 0 ? e.costCenterItems[k].costCenterItemOID : e.costCenterItems[0].costCenterItemOID,
            type: this.props.costAttribute,
            applicantOID: this.props.expenseReport.applicantOID,
            formOID: this.props.formOID,
            applicantJobId: this.props.expenseReport.applicantJobId,
            userOID: this.props.expenseReport.applicantOID,
          }]
               // 优先用这个接口的值
            baseService.getAlloctionUserByDepartment(params).then(resNew=>{
              if(resNew && resNew.data && resNew.data.fullName){
                if (resNew.data && resNew.data.fullName) {
                  e.personName = resNew.data.fullName;
                  e.relevantPerson = resNew.data.userOID;
                }
                let expenseApportion = this.state.expenseApportion;
                expenseApportion[k] = e;
                this.setState({
                  expenseApportion
                })
            }else{
              expenseReportService.getDefaultPeople({
            costCenterItemOId: k > 0 ? e.costCenterItems[k].costCenterItemOID : e.costCenterItems[0].costCenterItemOID,
            applicantOID: this.props.expenseReport.applicantOID,
            formOID: this.props.formOID,
            applicantJobId: this.props.expenseReport.applicantJobId,
            expenseTypeCode: this.state.expenseTypeCode
              }).then(result => {
            if (result && result.data) {
              e.personName = result.data.fullName;
              e.relevantPerson = result.data.userOID;
              let expenseApportion = this.state.expenseApportion;
              expenseApportion[k] = e;
              this.setState({
                expenseApportion
              })
            } else {
              if ((this.props.costAttribute === 'S' || this.props.costAttribute === 'D') && e.costCenterItems[0]) {
                if (this.props.costAttribute === 'S') {
                  baseService.getDoPeople({ costCenterItemOId: k > 0 ? e.costCenterItems[k].costCenterItemOID : e.costCenterItems[0].costCenterItemOID}).then(res => {
                    console.log(res)
                    if (res.data && res.data.fullName) {
                      e.personName = res.data.fullName;
                      e.relevantPerson = res.data.userOID;
                    } else {
                      console.log(2)
                      e.personName = undefined;
                      e.relevantPerson = undefined;
                    }
                    let expenseApportion = this.state.expenseApportion;
                    expenseApportion[k] = e;
                    this.setState({
                      expenseApportion
                    })
                  })
                } else if (this.props.costAttribute === 'D' && this.state.expenseTypeCode === 'MCD1008') {
                  expenseReportService.checkCenterIsCbi({costCenterItemOID: k > 0 ? e.costCenterItems[k].costCenterItemOID : e.costCenterItems[0].costCenterItemOID}).then(res => {
                    if (!res.data) {
                      console.log('expenseApportion', this.state.expenseApportion)
                      let expenseApportion = this.state.expenseApportion;
                      expenseApportion[k].costCenterItems[0] = [];
                      expenseApportion[k].personName = undefined;
                      expenseApportion[k].relevantPerson = undefined;
                      this.setState({
                        expenseApportion
                      })
                    }
                  })
                }
                // else {
                //   if (!e.id) {
                //     e.personName = undefined;
                //     e.relevantPerson = undefined;
                //     let expenseApportion = this.state.expenseApportion;
                //     expenseApportion[k] = e;
                //     this.setState({
                //       expenseApportion
                //     })
                //   }
                // }
              
              } else if (e.costCenterItems[0] && e.costCenterItems[0].costCenterItemOID) {
                expenseReportService.checkIsCenterItem(e.costCenterItems[0].costCenterItemOID, e.relevantPerson).then(res => {
                  console.log(res)
                  if (res.data.rows !== true) {
                    // console.log(4)
                    e.personName = undefined;
                    e.relevantPerson = undefined;
                    let expenseApportion = this.state.expenseApportion;
                    expenseApportion[k] = e;
                    this.setState({
                      expenseApportion
                    })
                  }
                });
              } else {
                console.log(`e===>`, e)
                e.personName = undefined;
                e.relevantPerson = undefined;
                let expenseApportion = this.state.expenseApportion;
                expenseApportion[k] = e;
                this.setState({
                  expenseApportion
                })
              }
            }
              })
            }
          })
        } else {
          arr.map((e, k) => {
            e.personName = undefined;
            e.relevantPerson = undefined;
            let expenseApportion = this.state.expenseApportion;
            expenseApportion[k] = e;
            this.setState({
              expenseApportion
            })
          })
        }
      });
    }
    this.setState({ columns, scrollX, expenseApportion: arr });
  };

  /*获取币种精度*/
  getCurrencyPrecision = (currencyCode = this.props.currencyCode) => {
    return queryCurrencyPrecision(currencyCode);
  };

  initExpenseApportion = (props, afterSetState = () => {}) => {
    const { value, actualApportionAmount, onChange, ownerOID } = props;
    const amount = this.props.amount;
    let amountActual = this.getActualApportionAmount(amount, actualApportionAmount);
    let { defaultExpenseApportion, loading, expenseApportion, expenseTypeId, currencyCode, expenseReportOID } = this.state;
    let currencyPrecision = this.getCurrencyPrecision();
    let refreshDefault = () => {
      this.setState({ loading: true });
      //获取报销单内费用类型的默认分摊项
      expenseReportService.getDefaultApportionment(props.expenseReportOID, props.expenseTypeId, amountActual, props.currencyCode, ownerOID, this.props.costAttribute)
        .then(res => {
          let defaultApportionmentList = res.data;
          defaultApportionmentList.map(item => {
            item.amount = Number((amountActual * item.proportion).toFixed(currencyPrecision));
          });

          /**
           * https://pmo.mcd.com.cn/jira/browse/TES-1489
           * 费用类型修改后保留之前的费用分摊。
           * 可能会有问题
           */
          const nextExpenseApportion = expenseApportion.length > 0 ? expenseApportion : defaultApportionmentList
          const isChange = nextExpenseApportion.map((e, k) => false);
          
          this.setState({
            defaultExpenseApportion: res.data[0],
            loading: false,
            expenseApportion: nextExpenseApportion,
            initApportionLock: true,
            expenseTypeId: props.expenseTypeId,
            expenseReportOID: props.expenseReportOID,
            currencyCode: props.currencyCode,
            isChange
          }, () => {
            afterSetState();
            onChange(nextExpenseApportion);
          });
        });
    };

    if (currencyCode !== props.currencyCode || (expenseTypeId !== props.expenseTypeId && props.expenseTypeId)) {
      refreshDefault();
    }
    if (!value || value.length === 0) {
      if (expenseReportOID && expenseTypeId && !defaultExpenseApportion && !loading) {
        refreshDefault();
      } else if (!loading && defaultExpenseApportion) {
        defaultExpenseApportion.amount = Number((defaultExpenseApportion.proportion * amountActual).toFixed(currencyPrecision));
        this.setState({
          expenseApportion: [defaultExpenseApportion],
          initApportionLock: false
        }, () => {
          afterSetState();
          onChange([defaultExpenseApportion]);
        });
      }
    } else if (!expenseApportion[0] && value && value.length > 0) {
      expenseApportion = [];
      value.map(item => {
        if (!this.props.amount) {
          if (actualApportionAmount) {
            item.amount = Number((actualApportionAmount * item.proportion).toFixed(currencyPrecision));
          } else {
            item.amount = Number((amount * item.proportion).toFixed(currencyPrecision));
          }
        }
        expenseApportion.push(item);
      });
      this.setState({ expenseApportion, defaultExpenseApportion: expenseApportion[0], initApportionLock: false }, () => afterSetState());
    } else if (expenseApportion[0]) {
      let apportionAmountSum = 0;
      expenseApportion.map(item => apportionAmountSum += Number(item.amount));
      apportionAmountSum = Number(apportionAmountSum.toFixed(currencyPrecision)); //解决浏览器计算精度问题
      expenseApportion.map(item => {
        if (apportionAmountSum !== (actualApportionAmount || amount)) {
          if (actualApportionAmount) {
            item.amount = Number((actualApportionAmount * item.proportion).toFixed(currencyPrecision));
          } else {
            item.amount = Number((amount * item.proportion).toFixed(currencyPrecision));
          }
        }
      });
      this.setState({
        expenseApportion,
        defaultExpenseApportion: expenseApportion[0],
        initApportionLock: false
      }, () => afterSetState());
    }
  };

  handleChangeCostCenter = async (result, index, costCenterIndex) => {
    console.log('result', result)
    if (result) {
      if (result.length === 0) {
        result[0] = {};
      }
      let { expenseApportion } = this.state;
      let costCenterItems = expenseApportion[index].costCenterItems[costCenterIndex];
      console.log('costCenterItems', costCenterItems)
      expenseApportion[index].personName = undefined;
      expenseApportion[index].relevantPerson = undefined;
      expenseApportion[index].finalPerson = undefined;
      expenseApportion[index].finalPersonName = undefined;
      if (costCenterItems) {
        let name = result[0].name;
        if (costCenterItems.costCenterOID === '00000000-0000-0000-0000-000000000000') {
          result[0].costCenterItemOID = result[0].departmentOid;
          if (!this.props.profile || !this.props.profile['department.full.path.disabled']) {
            name = result[0].path || result[0].name;
          }
          //分摊项中有成本中心
          if (expenseApportion[index].costCenterItems.length > 1) {
            baseService.checkCostCenterNeedEmpty().then(res => {
              if (res.data.visible) {
                expenseApportion[index].costCenterItems.map(item => {
                  if (item.costCenterOID !== '00000000-0000-0000-0000-000000000000') {
                    item.costCenterItemOID = null
                  }
                });
                this.setState({ expenseApportion })
              }
            })
          }
        }
        if (costCenterItems.type === 'father') { //父成本中心
          //如果修改父成本中心项，则子成本中心清空
          if (result[0].costCenterItemOID !== costCenterItems.costCenterItemOID) {
            expenseApportion[index].costCenterItems.map(item => {
              if (item.type === 'son') {
                item.costCenterItemOID = undefined;
              }
            });
          }
        }
        costCenterItems.costCenterItemOID = result[0].costCenterItemOID;
        costCenterItems.costCenterItemName = name;
        costCenterItems.name = name;
        costCenterItems.itemCode = result[0].custDeptNumber || result[0].code;
        expenseApportion[index].costCenterItems[costCenterIndex] = costCenterItems;
        let params = [{
          costCenterItemOID: costCenterItems.costCenterItemOID,
          type: this.props.costAttribute,
          applicantOID: this.props.expenseReport.applicantOID,
          formOID: this.props.formOID,
          applicantJobId: this.props.expenseReport.applicantJobId,
          userOID: this.props.expenseReport.applicantOID,
        }]
        // if (this.props.costAttribute === 'S') {
        //   baseService.getDoPeople({ costCenterItemOId: costCenterItems.costCenterItemOID}).then(res => {
        //     if (res.data) {
        //       expenseApportion[index].personName = res.data.fullName;
        //       expenseApportion[index].relevantPerson = res.data.userOID;
        //     }
        //     this.setState({ expenseApportion });
        //     this.props.onChange(expenseApportion);
        //   });
        // } else {
        //   this.setState({ expenseApportion });
        //   this.props.onChange(expenseApportion);
        // }

        // 优先用这个接口的值
        let newFullName;
        let newUserOID;
        const resNew = await baseService.getAlloctionUserByDepartment(params);
        if(resNew && resNew.data){
          let dataNew = resNew.data
          newFullName = dataNew.fullName
          newUserOID = dataNew.userOID
        }

        baseService.getBatchAlloctionUser(params).then(res => {
          if (res.data && res.data[0]) {
            expenseApportion[index].personName = newFullName || res.data[0].fullName;
            expenseApportion[index].relevantPerson = newUserOID || res.data[0].userOID;
          }
          this.setState({ expenseApportion });
          this.props.onChange(expenseApportion);
        })
      } else {
        let params = [{
          costCenterItemOID: result[0].costCenterItemOID,
          type: this.props.costAttribute,
          applicantOID: this.props.expenseReport.applicantOID,
          formOID: this.props.formOID,
          applicantJobId: this.props.expenseReport.applicantJobId,
          userOID: this.props.expenseReport.applicantOID,
        }]

        // 优先用这个接口的值
        let newFullName;
        let newUserOID;
        const resNew = await baseService.getAlloctionUserByDepartment(params);
        if(resNew && resNew.data){
          let dataNew = resNew.data
          newFullName = dataNew.fullName
          newUserOID = dataNew.userOID
        }

        baseService.getBatchAlloctionUser(params).then(res => {
          let newCostCenter = this.state.newCostCenter;
          newCostCenter[index] = result[0];
          let obj = {};
          obj.costCenterItemOID = result[0].costCenterItemOID;
          obj.costCenterItemName = result[0].name;
          obj.name = result[0].name;
          obj.itemCode = result[0].custDeptNumber || result[0].code;
          expenseApportion[index].costCenterItems[0] = obj;
          if (res.data && res.data[0]) {
            expenseApportion[index].personName = newFullName || res.data[0].fullName;
            expenseApportion[index].relevantPerson = newUserOID || res.data[0].userOID;
          }
          this.setState({ expenseApportion });
          this.props.onChange(expenseApportion);
        })
        // if (this.props.costAttribute === 'S') {
        //   baseService.getDoPeople({ costCenterItemOId: result[0].costCenterItemOID}).then(res => {
        //     let newCostCenter = this.state.newCostCenter;
        //     newCostCenter[index] = result[0];
        //     let obj = {};
        //     obj.costCenterItemOID = result[0].costCenterItemOID;
        //     obj.costCenterItemName = result[0].name;
        //     obj.name = result[0].name;
        //     obj.itemCode = result[0].custDeptNumber || result[0].code;
        //     expenseApportion[index].costCenterItems[0] = obj;
        //     if (res.data) {
        //       expenseApportion[index].personName = res.data.fullName;
        //       expenseApportion[index].relevantPerson = res.data.userOID;
        //     }
        //     this.setState({ expenseApportion });
        //     this.props.onChange(expenseApportion);
        //   });
        // } else {
        //   let newCostCenter = this.state.newCostCenter;
        //   newCostCenter[index] = result[0];
        //   let obj = {};
        //   obj.costCenterItemOID = result[0].costCenterItemOID;
        //   obj.costCenterItemName = result[0].name;
        //   obj.name = result[0].name;
        //   obj.itemCode = result[0].custDeptNumber || result[0].code;
        //   expenseApportion[index].costCenterItems[0] = obj;
        //   this.props.onChange(expenseApportion);
        //   this.setState({
        //     newCostCenter,
        //     expenseApportion
        //   });
        // }
      }
    }
  };

  handleChangeAmount = (result, index) => {
    if (typeof result === 'number' && !isNaN(result) && result !== 0) {
      let { expenseApportion } = this.state;
      let currencyPrecision = this.getCurrencyPrecision();
      let amount = Number(this.getActualApportionAmount()
        .toFixed(currencyPrecision));
      expenseApportion[index].amount = Number((result).toFixed(currencyPrecision));
      expenseApportion[index].proportion = (result / amount);
      this.setState({ expenseApportion });
      this.props.onChange(expenseApportion);
    }
  };

  handleChangeProportion = (result, index) => {
    if (typeof result === 'number' && !isNaN(result)) {
      let { expenseApportion } = this.state;
      let amount = this.getActualApportionAmount();
      let currencyPrecision = this.getCurrencyPrecision();
      expenseApportion[index].proportion = result / 100;
      expenseApportion[index].amount = Number((result / 100 * amount).toFixed(currencyPrecision));
      this.setState({ expenseApportion });
      this.props.onChange(expenseApportion);
    }
  };

  handleChangePerson = (result, index) => {
    let { expenseApportion } = this.state;
    // console.log(result)
    // console.log('handleChangePerson', result)
    console.log('handleChangePerson', this.state.expenseApportion)
    if (result[0]) {
      expenseApportion[index].relevantPerson = result[0].userOID;
      expenseApportion[index].personName = result[0].fullName;
      // expenseApportion[index].finalPerson = undefined;
      // expenseApportion[index].finalPersonName = undefined;
      // 关联人修改部门联动
      // let personInfo = result[0];
      // let currentApportion = expenseApportion[index];
      // let departmentItem = currentApportion.costCenterItems.filter(costCenter => {
      //   return costCenter.costCenterOID === '00000000-0000-0000-0000-000000000000'
      // })[0];
      // if (departmentItem && !departmentItem.costCenterItemOID) {
      //   departmentItem.costCenterItemOID = personInfo.departmentOID;
      //   departmentItem.costCenterItemName = personInfo.departmentName;
      //   let name = personInfo.departmentName;
      //   if (!this.props.profile || !this.props.profile['department.full.path.disabled']) {
      //     name = (personInfo.departmentPath || '').replace(/\|/img, ' | ');
      //   }
      //   if (name) {
      //     departmentItem.name = name;
      //     baseService.checkCostCenterNeedEmpty()
      //       .then(res => {
      //         if (res.data.visible) {
      //           currentApportion.costCenterItems.map(item => {
      //             if (item.costCenterOID !== '00000000-0000-0000-0000-000000000000') {
      //               item.costCenterItemOID = null
      //             }
      //           });
      //           this.setState({expenseApportion})
      //         }
      //       })
      //       .catch(() => {
      //         this.setState({expenseApportion});
      //       })
      //       .finally(() => {
      //         message.info(messages('my-account.key328')/*已更新分摊项部门为相关人部门*/);
      //       });
      //   }
      // }
      let arr = this.state.isChange;
      arr[index] = true;
      this.setState({ expenseApportion, isChange: arr });
      this.props.onChange(expenseApportion);
    }
  };
  handleChangeFinalPerson = (value, index) => {
    let { expenseApportion } = this.state;
    console.log('handleChangeFinalPerson', expenseApportion)
    // expenseApportion[index].finalPerson = value[0].fullName;
    // console.log(value, index);
    if (value.length && value[0]) {
      this.fetchVPAmount(value[0], index)
      expenseApportion[index].finalPerson = value[0].userOID;
      expenseApportion[index].finalPersonName = value[0].fullName;
      expenseApportion[index].finalPersonEmployeeID = value[0].employeeID;
      console.log('handleChangeFinalPerson', expenseApportion);
      this.setState({ expenseApportion }, () => {
        this.props.onChange(expenseApportion);
      });
    }
    // console.log(value, index)
  }
  //获取实际的分摊金额
  getActualApportionAmount = (oriAmount, amountActual) => {
    let { actualApportionAmount, amount } = this.props;
    let currencyPrecision = this.getCurrencyPrecision() || 2;
    if (typeof actualApportionAmount === 'number' || typeof amountActual === 'number') {
      if (typeof amountActual === 'number') {
        return Number(amountActual.toFixed(currencyPrecision));
      }
      return Number(actualApportionAmount.toFixed(currencyPrecision));
    } else {
      if (typeof oriAmount === 'number') {
        return Number(oriAmount.toFixed(currencyPrecision));
      }
      return Number(amount.toFixed(currencyPrecision));
    }
  };
  /**
   * 加载申请单的相关分摊行
   * */
  handleLoadingApplicationInvoice = (applicationApportionmentId) => {
    const showApplication = () => {
      const { expenseReportOID } = this.props;
      expenseReportService.getApplicationApportion(applicationApportionmentId, expenseReportOID)
        .then((res) => {
          const applicationApportion = res.data;
          this.setState({ applicationApportion });
        });
    };

    this.setState({ showApplication: true }, showApplication);
  };

  renderApplicationApportions = () => {
    const { applicationApportion } = this.state;
    let dataSource;
    !applicationApportion ? dataSource = []
      : dataSource = [{
        key: applicationApportion.applicationApportionmentId,
        unUsedAmount: applicationApportion.unUsedAmount,
        costCenterItems: applicationApportion.costCenterItems,
        applicationAmount: applicationApportion.applicationAmount,
      }];
    const columns = [
      {
        title: messages('my-account.key18')/*分摊项*/,
        dataIndex: 'costCenterItems',
        key: 'costCenterItems',
        render: (value) => {
          return (
            <Popover
              overlayStyle={{ maxWidth: 700 }}
              content={value.map((item) => {
                return <div> {item.costCenterName}：{item.costCenterItemName}</div>;
              })}
            >
            <div>
              {value.map((item) => {
                return <div> {item.costCenterName}：{item.costCenterItemName}</div>;
              })}
            </div>
            </Popover>
          );
        }
      },
      {
        title: messages('my-account.key185')/*申请金额*/,
        dataIndex: 'applicationAmount',
        key: 'applicationAmount',
      },
      {
        title: <span style={{ fontSize: 17 }}> {messages('my-account.key186')/*剩余未占金额*/}</span>,
        dataIndex: 'unUsedAmount',
        key: 'unUsedAmount',
      }
    ];
    return (
      !applicationApportion ?
        <Spin delay={500}/>
        : (<div>
          <Row style={{ margin: '10px' }}>
            <Col span={6}>
              {messages('components.key147'/*申请单号*/)}：{applicationApportion.businessCode}
            </Col>
            <If value={applicationApportion.applicationType === 1002}>
              <Col span={12}>
                {messages('request.key314'/*出差日期*/)}：{applicationApportion.startDate} ~ {applicationApportion.endDate}
              </Col>
            </If>
            <Col span={6}>
              {messages('financial-management.key131'/*申请人*/)}：{applicationApportion.applicantName}
            </Col>
          </Row>
          <Table
            style={{ margin: '20px' }}
            dataSource={dataSource}
            pagination={false}
            columns={columns}
            bordered
            size="small"
          />
        </div>)
    );
  };

  renderColumns = (record, attr, index) => {
    const { readOnly, costCenterItemsApportion } = this.props;
    const { defaultExpenseApportion } = this.state;
    let isEditable = defaultExpenseApportion && defaultExpenseApportion.isEditable;
    let isCostCenterItemEditable = defaultExpenseApportion && defaultExpenseApportion.isCostCenterItemEditable;
    let currencyPrecision = this.getCurrencyPrecision();
    switch (attr) {
      case 'costCenterRender':
        let labels = record.apportionmentLabels || [];
        return (
          <div className="department">
            <If value={labels.length > 0}>
              {labels.map((item, i) => {
                let color = 'blue';
                if (item.level === 'ERROR') color = 'red';
                return <Tag key={i} color={color}>{item.name}</Tag>;
              })}
            </If>
            {costCenterItemsApportion.map((costCenterItem, i) => {
              let isHaveItem = false;
              let costCenterItemIndex = undefined;
              record.costCenterItems && record.costCenterItems.map((item, indexCostCenterItems) => {
                if (item.costCenterOID === costCenterItem.costCenterOID) {
                  isHaveItem = true;
                  costCenterItemIndex = indexCostCenterItems;
                }
              });
              if (isHaveItem) {
                let isDepartment = (costCenterItem.costCenterOID === '00000000-0000-0000-0000-000000000000');
                return (
                  <InputGroup key={i} className="apportion-item-group">
                    <Popover content={costCenterItem.fieldName} placement="topLeft">
                      <Input
                        defaultValue={`${costCenterItem.fieldName}:`}
                        className="apportion-item-group-title"
                        disabled
                      />
                    </Popover>
                    {this.departmentCostCenterItem(record, index, costCenterItem, costCenterItemIndex, isDepartment)}
                  </InputGroup>
                );
              } else {
                let isDepartment = (costCenterItem.costCenterOID === '00000000-0000-0000-0000-000000000000');
                console.log('costCenterItem', costCenterItem, costCenterItemIndex)
                return (
                  <InputGroup key={i} className="apportion-item-group">
                    <Popover content={costCenterItem.fieldName} placement="topLeft">
                      <Input
                        defaultValue={`${costCenterItem.fieldName}:`}
                        className="apportion-item-group-title"
                        disabled
                      />
                    </Popover>
                    {this.departmentCostCenterItem(record, index, costCenterItem, costCenterItemIndex, undefined)}
                  </InputGroup>
                );
              }
            })}
          </div>
        );
      case 'amount':
        return readOnly ? formatNumber(record.baseCurrencyAmount) :
          <InputNumber className="apportion-amount"
                       onChange={(value) => this.handleChangeAmount(value, index)}
                       value={record.amount}
                       precision={currencyPrecision}
                       step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                       formatter={value => (typeof value === 'number' && !isNaN(value)) ? formatNumber(Number(value)) : formatNumber(value)}/>;
      case 'proportion':
        return readOnly ? `${(record.proportion * 100).toFixed(2)}%` :
          <InputNumber min={0}
                       className="expense-proportion-symbol"
                       precision={2}
                       step={0.01}
                       max={100}
                       onChange={(value) => this.handleChangeProportion(value, index)}
                       value={record.proportion * 100}
                       formatter={value => (typeof value === 'number' && !isNaN(value)) ? Number(value.toFixed(2)) : value}
          />;
      case 'personName':
        let user = [{
          fullName: record.personName,
          userOID: record.relevantPerson
        }];
        console.log('record', user)
        //新增一个判断条件 isEditable 或 isCostCenterItemEditable 为true时都可以编辑
        return (!readOnly && (isEditable || isCostCenterItemEditable) ? (
          <Chooser
            type={(this.props.costAttribute === 'D' || this.props.costAttribute === 'N') ? 'c5_people' : this.props.costAttribute === 'S' ? 'restaurant_people' : 'user'}
            value={record.personName ? user : []}
            valueKey="userOID"
            labelKey="fullName"
            listExtraParams={(this.props.costAttribute === 'D' || this.props.costAttribute === 'N') ? {
              costCenterItemOId: record.costCenterItems[0] && record.costCenterItems[0].costCenterItemOID ? record.costCenterItems[0].costCenterItemOID : this.state.newCostCenter[index] ? this.state.newCostCenter[index].costCenterItemOID : undefined,
              expenseReportOID: record.costCenterItems[0] && record.costCenterItems[0].fieldName && record.costCenterItems[0].fieldName === '费用承担项目' ? this.props.expenseReportOID : undefined,
              expenseTypeCode: this.state.expenseTypeCode
            } : this.props.costAttribute === 'S' ? {
              costCenterItemOId: record.costCenterItems[0] && record.costCenterItems[0].costCenterItemOID ? record.costCenterItems[0].costCenterItemOID : this.state.newCostCenter[index] ? this.state.newCostCenter[index].costCenterItemOID : undefined,
              expenseReportOID: record.costCenterItems[0] && record.costCenterItems[0].fieldName && record.costCenterItems[0].fieldName === '费用承担项目' ? this.props.expenseReportOID : undefined
            } : this.props.expenseTypeName.indexOf('滴滴') !== -1 ? {
              costCenterItemOId: record.costCenterItems[0] && record.costCenterItems[0].costCenterItemOID ? record.costCenterItems[0].costCenterItemOID : this.state.newCostCenter[index] ? this.state.newCostCenter[index].costCenterItemOID : undefined,
              isDidi: '1'
            } : this.props.costAttribute === 'B' ? {
              costCenterItemOId: record.costCenterItems[0] && record.costCenterItems[0].costCenterItemOID ? record.costCenterItems[0].costCenterItemOID : this.state.newCostCenter[index] ? this.state.newCostCenter[index].costCenterItemOID : undefined,
              expenseReportOID: record.costCenterItems[0] && record.costCenterItems[0].fieldName && record.costCenterItems[0].fieldName === '费用承担项目' ? this.props.expenseReportOID : undefined,
              isRestaurant: '1'
            } : {}}
            single
            showClear={false}
            onChange={(value) => this.handleChangePerson(value, index)}
          />
        ) : user[0].fullName);
      case 'operate':
        return (
          <div className="apportion-operate">
            <If value={isEditable && !readOnly}>
              <a onClick={() => this.handleCopyExpenseApportion(record)}
                 style={{ marginRight: 5 }}>
                {messages('common.copy')/*复制*/}
              </a>
            </If>
            <If value={!readOnly}>
              <a onClick={() => this.handleRemoveExpenseApportion(index)}>
                {messages('common.delete')/*删除*/}
              </a>
            </If>
            <If value={!!record.applicationApportionmentId}>
              <a
                onClick={() => this.handleLoadingApplicationInvoice(record.applicationApportionmentId)}
                style={{ marginRight: 5 }}>
                <Icon type="link"/>
                {messages('my-account.key187')/*申*/}
              </a>
            </If>
          </div>
        );
      case 'finalPerson':
        console.log(record);
        let finalUser = [{
          fullName: record.finalPersonName,
          employeeID: record.finalPersonEmployeeID,
          userOID: record.finalPerson
        }];
        let isFirst = false;
        let amount = 0;
        if (this.state.isChange[index]) {
          isFirst = true
        } else if (this.props.costAttribute === 'S') {
          baseService.getDoPeople({ costCenterItemOId: record.costCenterItems[0].costCenterItemOID}).then(res => {
            if (res.data) {
              isFirst = true
            }
          });
        }
        return (!readOnly && (isEditable || isCostCenterItemEditable) ? <Chooser
            type="gm_vp_officer"
            value={record.finalPersonName ? finalUser : []}
            valueKey="employeeID"
            labelKey="fullName"
            listExtraParams={{
              userOId: isFirst ? record.relevantPerson : undefined,
              applayUserOId: this.props.expenseReport.applicantOID
            }}
            single
            showClear={false}
            onChange={(value) => this.handleChangeFinalPerson(value, index)}
            renderPopoverContent={(value) => this.renderVpAmount(value, index)}
            renderValue={(value) => this.renderVpAmount(value, index)}
          /> : this.props.expenseTypeCode !== 'MCD1009' ? `${finalUser[0].fullName} (剩余额度: ${record.gmVpRemainAmount})` : finalUser[0].fullName)
      default:
        return null;
    }
  };

  fetchVPAmount = (value, index) => {
    console.log("value", value)
    const { vpAmountCache = {}, vpAmountList } = this.state
    if (value && value.userOID) {
      // if (typeof vpAmountCache[value.userOID] !== 'undefined') {
      //   return
      // }
      this.setState({
        vpAmountCache: {
          ...vpAmountCache,
          [value.userOID]: ''
        }
      })
      let params = {
        expenseTypeOid: this.props.expenseTypeOid,
        expenseId: this.props.expenseTypeId,
        date: moment(this.props.nowDate).format('YYYY/MM/DD'),
        userOId: value.userOID
      }
      expenseReportService.getRemainQuota(params).then(res => {
        if (res.status === 200) {
          vpAmountList[index] = Number(res.data).toFixed(2)
          this.setState({
            vpAmountCache: {
              ...vpAmountCache,
              [value.userOID]: Number(res.data).toFixed(2)
            },
            vpAmountList: vpAmountList
          });
        }
      })
    }
  }

  renderVpAmount = (value = [], index) => {
    if (value.length > 0) {
      const item = value[0]
      const { vpAmountCache = {}, vpAmountList } = this.state
      const amount = vpAmountCache[item.value.userOID]
      // 其他工作餐分摊行不要显示GM/VP/OFFICER的额度 TES-1811
      if (vpAmountList[index] && this.props.expenseTypeCode !== 'MCD1009') {
        // https://pmo.mcd.com.cn/jira/browse/TES-1295 
        return `${item.value.fullName} (剩余额度: ${vpAmountList[index] >= 0 ? formatNumber(vpAmountList[index]) : 0})`
      }
      return item.value.fullName
    }
 
    return ''
  }

  departmentCostCenterItem(record, index, constraint, costCenterIndex, isDepartment) {
    const { profile, readOnly, expenseTypeId, user, expenseReport, company, jobInfo: { departmentOID }, costAttribute } = this.props;
    const { defaultExpenseApportion, expenseApportion } = this.state;
    let isEditable = defaultExpenseApportion && defaultExpenseApportion.isEditable;
    let isCostCenterItemEditable = defaultExpenseApportion && defaultExpenseApportion.isCostCenterItemEditable;
    let fatherHasValue = true;
    record.costCenterItems.map(item => {
      if (item.type === 'father' && !item.costCenterItemOID) {
        fatherHasValue = false;
      }
    });
    let departmentItem,
      costCenterItems = null;
    if (isDepartment) {
      let departmentValue = {};
      record.costCenterItems.map(item => {
        if (item.costCenterOID === constraint.costCenterOID) {
          departmentValue = item;
        }
      });
      departmentValue.departmentOid = departmentValue.costCenterItemOID;
      departmentValue.name = departmentValue.costCenterItemName;
      let name = departmentValue.costCenterItemName ? departmentValue.costCenterItemName : '';
      let nameHtml = <Popover placement="topLeft" content={name}>{name}</Popover>;
      //新增一个判断条件 isEditable 或 isCostCenterItemEditable 为true时都可以编辑
      let extraParams = {
        companyOID: expenseReport.docCompanyOID || expenseReport.companyOID || company.companyOID,
        leafEnable: profile['department.leaf.selection.required']
      };

     let chooserItem = deepFullCopy(chooserData['department']);
      chooserItem.columns.some(item => {
        if (item.dataIndex === 'name') {
          item.render = (value, record) => {
            let user = configureStore.store.getState().login.user;
            let message = '';
            if ((!departmentOID && user.departmentOID === record.departmentOid) || (departmentOID && departmentOID === record.departmentOid)) {
              message = messages('components.key696')/*(我的)*/;
            }
            return (
              <Popover
                placement="topLeft"
                overlayStyle={{ maxWidth: 500 }}
                content={`${message}${record.path}`}>
                {message}{React.Component.prototype.checkFunctionProfiles('department.full.path.disabled', [undefined, false]) ? record.path : record.name}
              </Popover>
            );
          }
        }
      });
      departmentItem = (!readOnly && (isEditable || isCostCenterItemEditable)) ? (
        <Chooser
          selectorItem={chooserItem}
          valueKey="departmentOid"
          labelKey="name"
          className='department-select'
          single
          showClear
          itemMap
          onChange={department => this.handleChangeCostCenter(department, index, costCenterIndex)}
          value={departmentValue.costCenterItemOID ? [departmentValue] : []}
          listExtraParams={extraParams}
        />
      ) : <Input prefix={nameHtml} style={{ borderLeft: '0px', width: '70%' }} disabled/>;
    } else {
      let chooserItem = JSON.parse(JSON.stringify(chooserData['expense_cost_center_item']));
      chooserItem.key = 'costCenterItemOID';
      chooserItem.title = constraint.fieldName;
      chooserItem.searchForm = [{
        type: 'input',
        id: 'keyword',
        label: `${constraint.fieldName}${messages('my-account.key168')/*代码*/}/${messages('my-account.key167')/*名称*/}`
      }];
      chooserItem.columns = [{
        title: `${constraint.fieldName}${messages('my-account.key168')/*代码*/}`,
        dataIndex: 'code'
      }, {
        title: `${constraint.fieldName}${messages('my-account.key167')/*名称*/}`,
        dataIndex: 'name'
      }];
      chooserItem.url = `${config.baseUrl}/api/my/cost/center/items`;
      let departmentOID = expenseReport.departmentOID;
      expenseApportion[index].costCenterItems.map(item => {
        if (item.costCenterOID === '00000000-0000-0000-0000-000000000000') {
          departmentOID = item.costCenterItemOID || expenseReport.departmentOID;
        }
      });
      let listExtraParams = {
        costCenterOID: constraint.costCenterOID,
        userOID: expenseReport.applicantOID,
        companyOID: expenseReport.docCompanyOID,
        expenseTypeId,
        departmentOID,
        depart: costAttribute,
        costCenterItemOID: constraint.costCenterItemOID
      };
      let value = {};
      record.costCenterItems.map(item => {
        if (item.costCenterOID === constraint.costCenterOID || this.state.newCostCenter) {
          value = item;
        }
      });
      if (value.type === 'son') { //子成本中心取值依赖于已选的父成本中心OID
        record.costCenterItems.map(item => {
          if (item.type === 'father' && item.costCenterItemOID) {
            listExtraParams.parentCostCenterItemOID = item.costCenterItemOID;
          }
        });
      }
      if (this.state.expenseTypeCode === 'MCD1008') {
        listExtraParams.isMarketResearch = true
      }
      // https://pmo.mcd.com.cn/jira/browse/TES-2123
      // 公司活动的费用分摊行可编辑，但是只能有一个选项
      if (this.state.expenseTypeCode === 'MCD1011') {
        if (record.costCenterItems && record.costCenterItems.length > 0) {
          listExtraParams.keyword = record.costCenterItems[0].itemCode
        }
      }
      value.name = value.costCenterItemName;
      let name = value.costCenterItemName ? value.costCenterItemName : '';
      let nameHtml = <Popover placement="topLeft" content={name}>{name}</Popover>;
      //新增一个判断条件 isEditable 或 isCostCenterItemEditable 为true时都可以编辑
      costCenterItems = (!readOnly && (isEditable || isCostCenterItemEditable)) ? (
        <Chooser
          selectorItem={chooserItem}
          valueKey="costCenterItemOID"
          labelKey="name"
          single
          showClear
          itemMap
          listExtraParams={listExtraParams}
          disabled={value.type === 'son' && !fatherHasValue} //父成本中心没有值时，子成本中心不可编辑
          onChange={costCenterItem => this.handleChangeCostCenter(costCenterItem, index, costCenterIndex)}
          value={value.costCenterItemOID ? [value] : []}
        />
      ) : <Input prefix={nameHtml} style={{ borderLeft: '0px', width: '70%' }} disabled/>;
    }
    return isDepartment ? departmentItem : costCenterItems;
  }

  handleNewExpenseApportion = () => {
    let { expenseApportion, defaultExpenseApportion } = this.state;
    let defaultExpense = JSON.parse(JSON.stringify(defaultExpenseApportion));
    let accumulatorAmount = 0;
    if (expenseApportion.length) {
      accumulatorAmount = expenseApportion.map(item => Number(item.amount))
        .reduce((accumulator, currentValue) => accumulator + currentValue);
    }
    const currencyPrecision = this.getCurrencyPrecision();
    const totalAmount = this.getActualApportionAmount();
    defaultExpense.amount = Math.abs(totalAmount) > Math.abs(accumulatorAmount) ? (totalAmount - accumulatorAmount).toFixed(currencyPrecision) : 0;
    defaultExpense.proportion = Math.abs(totalAmount) > Math.abs(accumulatorAmount) ? (defaultExpense.amount / totalAmount).toFixed(4) : 0;
    defaultExpense.defaultApportion = false;
    defaultExpense.costCenterItems.map(item => {
      item.costCenterItemOID = null;
      item.departmentOid = null;
      item.costCenterItemName = null;
    });
    defaultExpense.apportionmentOID = null;
    defaultExpense.apportionmentLabels = [];
    defaultExpense.personName = undefined;
    defaultExpense.relevantPerson = undefined;
    defaultExpense.finalPerson = undefined;
    defaultExpense.finalPersonName = undefined;
    defaultExpense.finalPersonEmployeeID = undefined;
    expenseApportion.push(defaultExpense);
    this.setState({ expenseApportion });
    this.props.onChange(expenseApportion);
  };

  handleRemoveExpenseApportion = (index) => {
    let { expenseApportion } = this.state;
    if (index === 0 && expenseApportion.length > 1) {
      expenseApportion[1].defaultApportion = true;
      this.setState({ defaultExpenseApportion: expenseApportion[1] });
    }
    expenseApportion.splice(index, 1);
    this.setState({ expenseApportion });
    this.props.onChange(expenseApportion);
  };

  handleCopyExpenseApportion = (record) => {
    let { expenseApportion } = this.state;
    let target = JSON.parse(JSON.stringify(record));
    target.amount = 0;
    target.proportion = 0;
    target.apportionmentOID = null;
    target.defaultApportion = false;
    target.apportionmentOID = null;
    target.apportionmentLabels = [];
    expenseApportion.push(target);
    this.setState({ expenseApportion });
    this.props.onChange(expenseApportion);
  };
  //导入成功回调
  handleImportOk = () => {
    this.showImport(false);
  };
  //导入分摊Modal控制
  showImport = (flag) => {
    // 判断分摊行有一条数据时导入，要提示信息
    if (flag) {
      if (this.state.expenseApportion && this.state.expenseApportion.length > 0) {
        confirm({
          title: '提示',
          content: ' 友情提示，导入人员清单，历史导入的数据会自动清空，请确保最新导入数据完整无误，是否导入？',
          onOk: () => {
            // let list = []
            // this.setState({ showImportFrame: flag, expenseApportion: list }, () => {
            //   this.props.onChange(list);
            // });
            this.setState({ showImportFrame: flag })
          },
          onCancel() {},
        })
      } else {
        this.setState({ showImportFrame: flag });
      }
    } else {
      this.setState({ showImportFrame: flag });
    }
  };
  //切换上传模板上传模块
  switchUpload = () => {
    this.setState({
      tabKey: 'UPDATE'
    }, () => {
      this.setState({ tabKey: null })
    });
  };
  //处理导入回调
  handelImportCallBack = (result) => {
    let resultData = {};
    console.log('result', result)
    if (result.success) {
      let { expenseApportion } = this.state;
      let { invoiceOID } = this.props;
      let amount = this.getActualApportionAmount();
      let list = []
      if (result.result.length > 0) {
        result.result.map((item) => {
          item.proportion = (item.amount / amount).toFixed(4);
          item.expenseOID = invoiceOID;
          list.push(item)
          // expenseApportion.push(item);
        });
        list.map(e => {
          if (this.props.costAttribute === 'S' && !e.personName && !e.relevantPerson) {
            baseService.getDoPeople({ costCenterItemOId: e.costCenterItems[0].costCenterItemOID}).then(res => {
              console.log(res)
              if (res.data) {
                e.personName = res.data.fullName;
                e.relevantPerson = res.data.userOID;
              }
            })
          }
        })
        this.setState({ expenseApportion: list });
        this.props.onChange(list);
      }
      result.message && message.info(result.message);
      resultData.resultDom = (
        <div>{messages('my-account.key149', { arg1: result.result.length }/*导入成功：{arg1}条*/)}</div>
      );
      resultData.result = false;
    } else {
      let errorColumns = [
        {
          title: messages('my-account.key19'/*行号*/),
          dataIndex: 'rowNum',
          width: '13%'
        },
        {
          title: messages('my-account.key20'/*错误信息*/),
          dataIndex: 'errorMessage',
          render: (value) => <Popover content={value}>{value}</Popover>
        }];
      resultData.resultDom = (
        <div>
          <div>
            {
              result.result[0].rowNum === '-'
                ? <section>{messages('my-account.key280')/*导入失败*/}</section>
                : <section>
                  {result.result.length}{messages('my-account.key281')/*行导致导入失败*/}
                  <a style={{ fontSize: 14, marginLeft: 10 }} onClick={() => this.switchUpload(true)}> {messages('my-account.key282')/*请修改后重新导入*/}
                  </a>
                </section>
            }
          </div>
          <div>
            <Table rowKey={record => record.index}
                   columns={errorColumns}
                   dataSource={result.result}
                   pagination={false}
                   bordered
                   size="small"/>
          </div>
        </div>
      );
      resultData.result = false;
    }
    return resultData;
  };
  handleHeightReady = (height, index) => {
    const heights = [...this.state.heights];
    heights.push({
      index,
      height
    });
    this.setState({
      heights
    }, this.VListRef.recomputeRowHeights(index));
  };

  handleHoverChange = (visible) => {
    this.setState({ showApplication: visible });
  };

  /**
   * @desc 一键均摊功能,除不尽最后一位默认填充上
   */
  handleAverageExpenseApportion = (refresh) => {
    let { expenseApportion } = this.state;
    let { length } = expenseApportion;
    const currencyPrecision = this.getCurrencyPrecision() || 2;
    const totalAmount = this.getActualApportionAmount();

    let handleExpenseAverage = () => {
      expenseApportion.map((item, index) => {
        if (index === 0) {
          item.amount = (totalAmount / length).toFixed(currencyPrecision);
          item.proportion = item.amount / totalAmount;
        } else {
          let middleAmount = expenseApportion
            .slice(0, index)
            .map(item => item.amount)
            .reduce((accumulator, currentValue) => Number(accumulator) - Number(currentValue), totalAmount);
          if (Math.abs(middleAmount) > 0 && Math.abs(middleAmount) <= Math.abs(totalAmount) / length) {
            item.amount = middleAmount;
          } else if (Math.abs(middleAmount) > Math.abs(totalAmount) / length) {
            index + 1 === length ? item.amount = middleAmount : item.amount = (totalAmount / length);
          } else if (totalAmount > 0 && middleAmount <= 0 || totalAmount < 0 && middleAmount >= 0) {
            item.amount = 0;
          }
          if (index <= length) {
            item.amount = item.amount.toFixed(currencyPrecision);
            item.proportion = item.amount / totalAmount;
          } else {
            item.proportion = item.amount / totalAmount;
            item.amount = item.amount.toFixed(currencyPrecision);
          }
        }
      });
      this.setState({ expenseApportion });
      this.props.onChange(expenseApportion);
    };
    (length === 0 || length === 1) && !refresh ? message.warning(messages('my-account.key190')/*请先新增分摊行*/) : handleExpenseAverage();
  };

  // 批量新增分摊，显示弹窗
  handleAddNewExpenseApportion = () => {
    this.setState({
      showListSelectVisible: true,
      // modalKey: this.state.modalKey + 1
    });
  }

  handleListSelectCancel = () => {
    this.setState({
      showListSelectVisible: false,
      // modalKey: this.state.modalKey + 1
    });
  }

  handleListSelectOk = (value) => {
    let arr = [];
    this.state.expenseApportion.map((e, k) => {
      if (e.costCenterItems[0] && e.costCenterItems[0].costCenterItemOID) {
        arr.push(e.costCenterItems[0].costCenterItemOID);
      }
    });
    let { expenseApportion, defaultExpenseApportion } = this.state;
    if (value) {
      // value.map((e, k) => {
      //   console.log(e)
      //   if (arr.length > 0) {
      //     if (arr.indexOf(e.costCenterItemOID) == -1) {
      //       let defaultExpense = JSON.parse(JSON.stringify(defaultExpenseApportion));
      //       console.log('defaultExpense111111111', defaultExpense)
      //       let accumulatorAmount = 0;
      //       if (expenseApportion.length) {
      //         accumulatorAmount = expenseApportion.map(item => Number(item.amount))
      //           .reduce((accumulator, currentValue) => accumulator + currentValue);
      //       }
      //       const currencyPrecision = this.getCurrencyPrecision();
      //       const totalAmount = this.getActualApportionAmount();
      //       defaultExpense.amount =  0;
      //       defaultExpense.proportion = 0;
      //       defaultExpense.defaultApportion = false;
      //       defaultExpense.costCenterItems.map(item => {
      //         item.costCenterItemOID = e.costCenterItemOID;
      //         item.departmentOid = null;
      //         item.costCenterItemName = e.name;
      //         item.itemCode = e.code;
      //         item.name = e.name;
      //       });
      //       if (this.props.costAttribute === 'S') {
      //         baseService.getDoPeople({ costCenterItemOId: e.costCenterItemOID}).then(res => {
      //           console.log(res)
      //           if (res.data) {
      //             expenseApportion[k + 1].personName = res.data.fullName;
      //             expenseApportion[k + 1].relevantPerson = res.data.userOID;
      //           }
      //           this.setState({ expenseApportion });
      //           this.props.onChange(expenseApportion);
      //         })
      //       } else {
      //         defaultExpense.personName = undefined;
      //         defaultExpense.relevantPerson = undefined;
      //       }
      //       defaultExpense.apportionmentOID = null;
      //       defaultExpense.apportionmentLabels = [];
      //       defaultExpense.finalPerson = undefined;
      //       defaultExpense.finalPersonName = undefined;
      //       expenseApportion.push(defaultExpense);
      //       console.log('expenseApportion', expenseApportion)
      //       this.setState({ expenseApportion });
      //       this.props.onChange(expenseApportion);
      //     }
      //   } else { 
      //       let defaultExpense = {
      //         costCenterItems: [],
      //         defaultApportion: false,
      //         isEditable: true,
      //         proportion: 0
      //       };
      //       let accumulatorAmount = 0;
      //       if (expenseApportion.length) {
      //         accumulatorAmount = expenseApportion.map(item => Number(item.amount))
      //           .reduce((accumulator, currentValue) => accumulator + currentValue);
      //       }
      //       const currencyPrecision = this.getCurrencyPrecision();
      //       const totalAmount = this.getActualApportionAmount();
      //       defaultExpense.amount =  0;
      //       defaultExpense.proportion = 0;
      //       defaultExpense.defaultApportion = false;
      //       defaultExpense.costCenterItems = [{
      //         costCenterItemOID: e.costCenterItemOID,
      //         departmentOid: null,
      //         costCenterItemName: e.name,
      //         itemCode: e.code,
      //         name: e.name
      //       }]
      //       if (this.props.costAttribute === 'S') {
      //         baseService.getDoPeople({ costCenterItemOId: e.costCenterItemOID}).then(res => {
      //           console.log(res)
      //           if (res.data) {
      //             expenseApportion[k].personName = res.data.fullName;
      //             expenseApportion[k].relevantPerson = res.data.userOID;
      //           }
      //           this.setState({ expenseApportion });
      //           this.props.onChange(expenseApportion);
      //         })
      //       } else {
      //         defaultExpense.personName = undefined;
      //         defaultExpense.relevantPerson = undefined;
      //       }
      //       defaultExpense.apportionmentOID = null;
      //       defaultExpense.apportionmentLabels = [];
      //       defaultExpense.finalPerson = undefined;
      //       defaultExpense.finalPersonName = undefined;
      //       expenseApportion.push(defaultExpense);
      //       console.log('expenseApportion', expenseApportion)
      //       this.setState({ expenseApportion });
      //       this.props.onChange(expenseApportion);
      //     }
        
      // })

      let trueList = [];
      let centetList = [];
      if (arr.length > 0) {
        value.map(item => {
          if (!arr.includes(item.costCenterItemOID)) {
            trueList.push({
              costCenterItemOID: item.costCenterItemOID,
              type: this.props.costAttribute,
              applicantOID: this.props.expenseReport.applicantOID,
              formOID: this.props.formOID,
              applicantJobId: this.props.expenseReport.applicantJobId
            })
            centetList.push(item)
          }
        })
      } else {
        value.map(item => {
          trueList.push({
            costCenterItemOID: item.costCenterItemOID,
            type: this.props.costAttribute,
            applicantOID: this.props.expenseReport.applicantOID,
            formOID: this.props.formOID,
            applicantJobId: this.props.expenseReport.applicantJobId
          })
          centetList.push(item)
        })
      }
      let trueData = [];
      baseService.getBatchAlloctionUser(trueList).then(res => {
        console.log("res", res)
        if (res.data) {
          res.data.map(item => {
            trueList.map(b => {
              if (item.costCenterItemOID === b.costCenterItemOID) {
                let defaultExpense = {
                  costCenterItems: [],
                  defaultApportion: false,
                  isEditable: true,
                  proportion: 0,
                  amount: 0,
                  personName: item.fullName,
                  relevantPerson: item.userOID,
                  finalPerson: undefined,
                  finalPersonName: undefined,
                  apportionmentOID: undefined,
                  apportionmentLabels: []
                };
                let accumulatorAmount = 0;
                if (expenseApportion.length) {
                  accumulatorAmount = expenseApportion.map(item => Number(item.amount))
                    .reduce((accumulator, currentValue) => accumulator + currentValue);
                }
                let centerData = undefined;
                value.map(a => {
                  if (a.costCenterItemOID === item.costCenterItemOID) {
                    centerData = a;
                  }
                })
                defaultExpense.costCenterItems = [{
                  costCenterItemOID: centerData.costCenterItemOID,
                  departmentOid: null,
                  costCenterItemName: centerData.name,
                  itemCode: centerData.code,
                  name: centerData.name
                }]
                expenseApportion.push(defaultExpense);
              }
            })
          })
          this.setState({ expenseApportion });
          this.props.onChange(expenseApportion);
          this.handleAverageExpenseApportion(true);
        }
      })
    }
    // this.setState({ expenseApportion });
    this.setState({
      showListSelectVisible: false,
      // expenseApportion
      // modalKey: this.state.modalKey + 1
    }, () => {
      
    });
    // this.props.onChange(expenseApportion);
  }

  emptyPersonName = (index) => {
    let { expenseApportion } = this.state;
    expenseApportion[index].personName = undefined;
    expenseApportion[index].relevantPerson = undefined;
    this.setState({
      expenseApportion
    });
    this.props.onChange(expenseApportion);
  }

  getPersonName = (record) => {
    expenseReportService.checkIsCenterItem(record.costCenterItems[0].costCenterItemOID, record.relevantPerson).then(res => {
      console.log(res)
      // if (res.data.rows) {
      //   return [{
      //     fullName: record.personName,
      //     userOID: record.relevantPerson
      //   }]
      // } else {

      // }
      return [{
        fullName: record.personName,
        userOID: record.relevantPerson
      }]
    })
  }

  handleDeleteExpenseApportion = () => {
    const { expenseApportion, selectedRowKeys } = this.state;
    let data = [];
    expenseApportion.map((item, k) => {
      if (!selectedRowKeys.includes(k)) {
        data.push(item)
      }
    });
    this.setState({
      expenseApportion: data,
      selectedRowKeys: undefined
    });
    this.props.onChange(data);
    console.log("deleteIndex", data)
  }

  onSelectChange = (selectedRowKeys) => {
    console.log('selectedRowKeys', selectedRowKeys)
    this.setState({
      selectedRowKeys
    })
  }

  handleDownLoadExpenseApportion = () => {
    
  }
  

  render() {
    const { loading, columns, expenseApportion, defaultExpenseApportion, scrollX, showImportFrame, tabKey, showListSelectVisible, selectedRowKeys } = this.state;
    const { readOnly, expenseReportOID, expenseTypeId, profile, actualApportionAmount, currencyCode, expenseReport,
      apportionEnable, receiptList, amount, ownerOID ,taxRate} = this.props;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14, offset: 1 },
    };
    let showActualAmount = false;
    let extraAmountTip = '';
    let currencyPrecision = this.getCurrencyPrecision();
    let apportionedAmount = 0; //分摊行金额总和
    expenseApportion && expenseApportion.map(item => apportionedAmount += Number(item.amount || 0));
    if (typeof actualApportionAmount === 'number' && profile['all.total.amount.apportionment'] === false) {
      showActualAmount = true;
      let temp = `${currencyCode} ${actualApportionAmount.toFixed(currencyPrecision)}`;
      let receiptFee = 0;
      let popoverContent = '';
      if (receiptList[0]) {
        receiptList.map(item => receiptFee += (item.fee / 100).toFixed(currencyPrecision));
        if (amount < receiptFee) { //不足额报销：费用金额 小于 所关联的发票金额总和
          if (profile['expense.Insufficient.deductible.all.enabled']) {
            popoverContent = messages('my-account.key192')/*分摊金额 = 费用金额 - N张发票的税额之和*/
          } else {
            popoverContent = messages('my-account.key248')/*分摊金额 = 费用金额 - 发票税额总和 * 费用金额 / 发票价税合计总和*/
          }
        } else { //足额报销
          popoverContent = messages('my-account.key192')/*分摊金额 = 费用金额 - N张发票的税额之和*/
        }
      } else {
        popoverContent = messages('my-account.key245',{arg1:(Math.round(Number(taxRate) + 'e' + 4)) / Math.pow(10, 2)})/*分摊金额=费用金额 /（1+{arg1}%）*/;
      }
      extraAmountTip = (
        <div className="extra-amount-tip">
          <Popover content={popoverContent}><Icon type="info-circle" className="tip-icon"/></Popover> {messages('my-account.key193')/*分摊金额总计*/}：<span className="tip-amount">{temp}</span>
        </div>
      )
    }
    /**
     * @desc 增加条件判断 后端将所有的分摊行都释放。1：是否有分摊行权限，2：分摊数据中是否有关联的申请单分摊行OID （待优化）
     */
    let isRelatedApplication = () => {
      return expenseApportion && expenseApportion.some(item => !!item.applicationApportionmentId);
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    let downLoadList = [];
    expenseApportion && expenseApportion.map(item => {
      downLoadList.push({
        itemCode: item.costCenterItems && item.costCenterItems[0] && item.costCenterItems[0].itemCode,
        amount: item.amount,
        eid: item.relevantPerson
      })
    })
    return (
      (isRelatedApplication() || apportionEnable) ?
        <div className="expense-apportion">
          <FormItem {...formItemLayout} label={messages('my-account.key22'/*费用分摊*/)}
                    extra={showActualAmount && expenseReport.status === 1001 ? extraAmountTip : ''}
                    style={{ marginBottom: 12 }}/>
          {loading ? <Spin/> : (
            <div>
              <Popover
                overlayStyle={{ maxWidth: 700 }}
                content={this.renderApplicationApportions()}
                title={messages('my-account.key188')/*申请单分摊行*/}
                trigger="click"
                visible={this.state.showApplication}
                onVisibleChange={this.handleHoverChange}
              >
                <Table columns={columns}
                       dataSource={expenseApportion}
                       bordered
                       size="small"
                       rowClassName="apportion-row"
                       rowKey={(record, index) => index}
                      //  rowSelection={rowSelection}
                       scroll={{ x: scrollX }}
                       pagination={false}/>
              </Popover>
              <If
                value={!readOnly && defaultExpenseApportion && defaultExpenseApportion.isEditable}>
                <Row>
                  <Col span={window.ISIE9 ? 12 : 4}>
                    <div className="new-expense-apportion" onClick={this.handleNewExpenseApportion}>
                      <Icon type="plus"/>{messages('my-account.key23'/*新建分摊*/)}
                    </div>
                  </Col>
                  <If value={!window.ISIE9}>
                    <Col span={6}>
                      <div className="new-expense-apportion" onClick={this.handleAddNewExpenseApportion}>
                        <Icon type="plus"/>{messages('my-account.key394'/*批量新增分摊*/)}
                      </div>
                    </Col>
                  </If>
                  <If value={!window.ISIE9}>
                    <Col span={6}>
                      <div className="new-expense-apportion" onClick={() => this.showImport(true)}>
                        <Icon type="plus"/>{messages('my-account.key24'/*导入分摊*/)}
                      </div>
                    </Col>
                  </If>
                  <Col span={window.ISIE9 ? 12 : 4}>
                    <div className="new-expense-apportion" onClick={this.handleAverageExpenseApportion}>
                          {messages('my-account.key194')/*一键均摊*/}
                    </div>
                  </Col>
                  {/* <Col span={window.ISIE9 ? 12 : 4}>
                    <div className="new-expense-apportion" onClick={this.handleDeleteExpenseApportion}>
                          {messages('my-account.key398')}
                    </div>
                  </Col> */}
                  <Col span={window.ISIE9 ? 12 : 4}>
                    <ExportModal
                      type="expense"
                      btnSize="small"
                      btnIcon="download"
                      exportTitle={messages('my-account.key399')}
                      exportType={"SHARE_ROW"}
                      exportCommand={"SHARE_ROW"}
                      exportCondition={{
                        shareDownloadCommand: {
                          data: downLoadList
                        },
                      }}
                    />
                  </Col>
                </Row>
              </If>
            </div>
          )}
          <Importer visible={showImportFrame}
                    templateUrl={`${config.baseUrl}/api/apportion/template?expenseReportOID=${expenseReportOID}`}
                    uploadUrl={`${config.baseUrl}/api/apportion/import?expenseReportOID=${expenseReportOID}&expenseTypeID=${expenseTypeId}&ownerOID=${ownerOID}`}
                    accept=".xlsx"
                    isImporterResultDom={true}
                    tabKey={tabKey}
                    downFileName={messages('my-account.key25'/*分摊模板文件*/)}
                    callBackResult={this.handelImportCallBack}
                    fileName={messages('my-account.key195')/*EXCEL文件*/}
                    uploadParams={{amount: actualApportionAmount || amount, apportionedAmount: 0}}
                    onOk={this.handleImportOk}
                    afterClose={() => this.showImport(false)}/>
          {/* <ListSelector
            visible={showListSelectVisible}
            type="expense_cost_center_item"
            onCancel={this.handleListSelectCancel}
            onOk={this.handleListSelectOk}
            selectedData={[]}
            extraParams={{
              // costCenterOID: constraint.costCenterOID,
              userOID: this.props.expenseReport.applicantOID,
              companyOID: this.props.expenseReport.docCompanyOID,
              expenseTypeId: this.props.expenseTypeId,
              departmentOID: this.props.departmentOID,
              depart: this.props.costAttribute === 'D' ? 1 : this.props.costAttribute === 'S' ? 2 : 3
            }}
            single={false}
            valueKey="costCenterItemOID"
            labelKey="name"
            showDetail
            showArrow={false}
            additionalDefault={[]}
            method='get'
          /> */}
          <ExpenseTransfer
            visible={showListSelectVisible}
            onOk={this.handleListSelectOk}
            onCancel={this.handleListSelectCancel}
            extraParams={{
              costCenterOID: this.props.costCenterItemsApportion[0].costCenterOID,
              userOID: this.props.expenseReport.applicantOID,
              companyOID: this.props.expenseReport.docCompanyOID,
              expenseTypeId: this.props.expenseTypeId,
              departmentOID: this.props.departmentOID,
              depart: this.props.costAttribute,
              costCenterItemOID: this.props.costCenterItemsApportion[0].costCenterItemOID
            }}
            locale={this.props.language.locale}
            key={this.state.modalKey}
          />
        </div> : <div/>
    );
  }

}

ExpenseApportion.propTypes = {
  value: React.PropTypes.array,
  amount: React.PropTypes.number,
  expenseReportOID: React.PropTypes.string,
  formOID: React.PropTypes.string,
  invoiceOID: React.PropTypes.string,
  expenseTypeId: React.PropTypes.any,
  onChange: React.PropTypes.func,
  readOnly: React.PropTypes.bool,
  costCenterItemsApportion: React.PropTypes.array,
  actualApportionAmount: React.PropTypes.any,//实际的分摊金额,用于显示分摊金额提醒，如果类型为数字才显示
  currencyCode: React.PropTypes.string,//币种
  ownerOID: React.PropTypes.string, //费用归属人
  expenseReport: React.PropTypes.object, //报销单详情
  apportionEnable: React.PropTypes.bool, // 判断是开启分摊行
  receiptList: React.PropTypes.array, //发票列表
};

ExpenseApportion.defaultProps = {
  costCenterItemsApportion: []
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    profile: state.login.profile,
    user: state.login.user,
    language: state.main.language,
  };
}

export default connect(mapStateToProps)(ExpenseApportion);
